package com.yange.accountbook.ui

import android.content.Context
import android.content.Intent
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lxj.xpopup.XPopup
import com.yange.accountbook.R
import com.yange.accountbook.databinding.BookDetailLayoutBinding
import com.yange.accountbook.entity.AccountEntity
import com.yange.accountbook.entity.BooksEntity
import com.yange.accountbook.entity.IconEntity
import com.yange.accountbook.events.AccountDetailChangeEvent
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.popup.IconPopup
import com.yange.accountbook.ui.adapter.AccountListAdapter
import com.yange.accountbook.utils.StringUtils
import com.yange.accountbook.utils.showToast
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener
import com.zhuangku.app.widget.EmptyView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * 账本详情
 */
class BookDetailActivity : BaseActivity<BookDetailLayoutBinding>() {

    lateinit var emptyView: EmptyView

    lateinit var myAdapter: AccountListAdapter

    lateinit var localBook: BooksEntity


    override fun getViewBinding() = BookDetailLayoutBinding.inflate(layoutInflater)

    override fun init() {

        localBook = intent.getParcelableExtra("book")!!

        emptyView = EmptyView(this)
        myAdapter = AccountListAdapter()
        myAdapter.setEmptyView(emptyView)


        initListener()

        binding.listAccount.layoutManager = LinearLayoutManager(this)
        binding.listAccount.adapter = myAdapter
        refreshView()
    }

    companion object {
        fun start(context: Context, book: BooksEntity) {
            var intent = Intent(context, BookDetailActivity().javaClass)
            intent.putExtra("book", book)
            context.startActivity(intent)
        }

    }

    /**
     * 刷新明细
     * 刷新标题
     */
    private fun refreshView() {
        getAccountList()
    }


    private fun refreshTitleBar() {
        binding.tvAdd.setTitle(StringUtils.buildMoneyTitleBar(localBook.name, localBook.money))
    }

    //初始化页面监听器
    private fun initListener() {
        //明细变更事件
        EventBus.getDefault().register(this)

        //添加icon点击
        myAdapter.addChildClickViewIds(R.id.layout_book_icon)
        myAdapter.setOnItemChildClickListener() { adapter, view, position ->

            var item = adapter.getItem(position) as AccountEntity
            //修改账户
            if (view.id == R.id.layout_book_icon) {
                XPopup.Builder(this)
                    .asCustom(IconPopup(this, object : IconPopup.AddListener {
                        override fun success(icon: IconEntity) {
                            update(icon.icon, icon.name, icon.bizId)
                        }
                    }, IconEntity(item.icon, item.name, item.id)))
                    .show()

            }
        }

        myAdapter.setOnItemClickListener { adapter, view, position ->
            var item = adapter.getItem(position) as AccountEntity
            AccountDetailActivity.start(this, item)
        }


        //下拉刷新监听
        binding.smartRefresh.setOnRefreshListener {
            getAccountList()
        }

        //新增账户监听
        binding.tvAdd.setOnClickListener {
            XPopup.Builder(this)
                .asCustom(
                    IconPopup(
                        this,
                        object : IconPopup.AddListener {
                            override fun success(icon: IconEntity) {
                                commit(icon.icon, icon.name)
                            }
                        },
                        IconEntity()
                    )
                )
                .show()
        }
        initItemMoveListener()
        initItemSwipeListener();
    }

    fun initItemMoveListener() {
        binding.listAccount.isLongPressDragEnabled = true
        binding.listAccount.setOnItemMoveListener(object : OnItemMoveListener {
            override fun onItemMove(
                srcHolder: RecyclerView.ViewHolder?,
                targetHolder: RecyclerView.ViewHolder?
            ): Boolean {
                // 此方法在Item拖拽交换位置时被调用。
                // 第一个参数是要交换为之的Item，第二个是目标位置的Item。
                // 交换数据，并更新adapter。
                val fromPosition = srcHolder!!.adapterPosition
                val toPosition = targetHolder!!.adapterPosition
                Collections.swap(myAdapter.data, fromPosition, toPosition)
                myAdapter.notifyItemMoved(fromPosition, toPosition)
                //这里先改本地数据，然后再悄悄该后台数据，不然操作不流畅
                changeSort()
                // 返回true，表示数据交换成功，ItemView可以交换位置。
                return true
            }

            override fun onItemDismiss(srcHolder: RecyclerView.ViewHolder?) {


            }
        })
    }

    fun initItemSwipeListener() {
        var swipeMenuCreator =
            SwipeMenuCreator { leftMenu, rightMenu, position ->
                var deleteItem = SwipeMenuItem(this)
                deleteItem.height = ViewGroup.LayoutParams.MATCH_PARENT
                deleteItem.width = 200
                deleteItem.textSize = 12
                deleteItem.setBackground(R.color.my_red)
                this?.getColor(R.color.text_white).let {
                    it?.let { it1 ->
                        deleteItem.setTextColor(
                            it1
                        )
                    }
                }
                deleteItem.text = "删除"
                rightMenu?.addMenuItem(deleteItem)
            }
        binding.listAccount.setSwipeMenuCreator(swipeMenuCreator)
        binding.listAccount.setOnItemMenuClickListener { menuBridge, adapterPosition ->
            menuBridge?.closeMenu()
            // 左侧还是右侧菜单：
            val direction = menuBridge!!.direction
            // 菜单在Item中的Position：
            val menuPosition = menuBridge.position
            if (direction == -1 && menuPosition == 0) {
                XPopup.Builder(this)
                    .autoOpenSoftInput(true)
                    .dismissOnTouchOutside(true)
                    .asConfirm(
                        "提示", "确认删除" + myAdapter.data[adapterPosition].name + "吗"
                    ) {
                        deleteAccount(myAdapter.data[adapterPosition].id)
                    }
                    .show()

            }
        }
    }

    private fun deleteAccount(id: Int) {
        var arrayList = ArrayList<Int>()
        arrayList.add(id)
        RetrofitClient.getInstance().deleteRecord(this, Api.ACCOUNT_DELETE, arrayList)
            .subscribe(object : RecObserver<BaseResponse<Any>>(this, true, false) {
                override fun onSuccess(t: BaseResponse<Any>?) {
                    showToast("删除成功")
                    EventBus.getDefault().post(AccountDetailChangeEvent(localBook.id, id))
                    refreshView()
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

    fun changeSort() {
        RetrofitClient.getInstance().accountSort(
            this, Api.ACCOUNT_SORT,
            myAdapter.data as java.util.ArrayList<AccountEntity>?
        ).subscribe(object : RecObserver<BaseResponse<Any>>(this, false, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {}
            override fun onFail(msg: String, code: Int) {}
        })
    }


    /**
     * 1.刷新账本信息
     * 2.刷新页面数据
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAccountDetailChange(event: AccountDetailChangeEvent) {
        refreshBookInfo(event.bookId)
        refreshView()
    }

    //刷新标题，根据账本id获取账户信息
    private fun refreshBookInfo(bookId: Int) {
        RetrofitClient.getInstance().invokeGetBookInfo(this, localBook.id)
            .subscribe(object : RecObserver<BaseResponse<BooksEntity>>(this, true, false) {
                override fun onSuccess(t: BaseResponse<BooksEntity>?) {
                    localBook = t?.data!!
                    refreshTitleBar()
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }

            })
    }


    private fun update(icon: String, name: String, id: Int) {
        RetrofitClient.getInstance().invokePostBody(
            this, Api.ACCOUNT_UPDATE, mapOf(
                "id" to id,
                "icon" to icon,
                "name" to name
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(this, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                getAccountList()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }

        })
    }

    //新建账户
    private fun commit(icon: String, name: String) {
        RetrofitClient.getInstance().invokePostBody(
            this, Api.ACCOUNT_SAVE, mapOf(
                "bookId" to localBook.id,
                "icon" to icon,
                "name" to name
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(this, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                getAccountList()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }

        })
    }


    /**
     * 账户列表
     */
    private fun getAccountList() {
        RetrofitClient.getInstance()
            .invokePostBody(this, Api.ACCOUNT_LIST, mapOf("bookId" to localBook.id))
            .subscribe(object : RecObserver<BaseResponse<List<AccountEntity>>>(this, false, false) {
                override fun onSuccess(t: BaseResponse<List<AccountEntity>>?) {
                    binding.smartRefresh.finishRefresh()
                    myAdapter.setNewInstance(t?.data as MutableList<AccountEntity>?)
                }

                override fun onFail(msg: String, code: Int) {
                    binding.smartRefresh.finishRefresh()
                    showToast(msg)
                }
            })
    }


}